// cloudfunctions/updateCollection/index.js
const cloud = require('wx-server-sdk');
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
  })
const db = cloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  try {
    const { action, userId, goodsId } = event;
    
    // 验证参数
    if (!action || !userId || !goodsId) {
      return { success: false, message: '参数不完整' };
    }
    
    // 操作类型验证
    if (action !== 'add' && action !== 'remove') {
      return { success: false, message: '操作类型错误' };
    }
    
    // 数据库事务保证原子性
    return await db.runTransaction(async (transaction) => {
      // 检查用户收藏状态
      const collectionRes = await transaction.collection('user_collections')
        .where({ user_id: userId, item_id: goodsId })
        .get();
      
      if (action === 'add') {
        // 添加收藏
        if (collectionRes.data.length > 0) {
          return { success: false, message: '已收藏该商品' };
        }
        
        // 添加收藏记录
        await transaction.collection('user_collections').add({
          data: {
            user_id: userId,
            item_id: goodsId,
            createTime: db.serverDate()
          }
        });
        
        // 更新商品收藏数
        await transaction.collection('blindbox_goods')
          .doc(goodsId)
          .update({
            data: {
              collectCount: _.inc(1)
            }
          });
          
        return { success: true, message: '收藏成功' };
        
      } else {
        // 取消收藏
        if (collectionRes.data.length === 0) {
          return { success: false, message: '未收藏该商品' };
        }
        
        // 删除收藏记录
        await transaction.collection('user_collections')
          .where({ user_id: userId, item_id: goodsId })
          .remove();
        
        // 更新商品收藏数
        await transaction.collection('blindbox_goods')
          .doc(goodsId)
          .update({
            data: {
              collectCount: _.inc(-1)
            }
          });
          
        return { success: true, message: '取消收藏成功' };
      }
    });
  } catch (error) {
    console.error('收藏操作失败', error);
    return { 
      success: false, 
      message: error.message || '服务器错误',
      error: error.message
    };
  }
};